<script id="draw-shader-vs" type="x-shader/x-vertex">
precision mediump float;
attribute vec3 inPos;
attribute vec3 inNV;
attribute vec2 inTex;
varying float NdotL;
varying vec2 texCoord;

uniform mat4 u_projectionMat44;
uniform mat4 u_viewMat44;
uniform mat4 u_modelMat44;
uniform vec3 u_lightDir;

void main()
{
    vec3  modelNV = mat3( u_modelMat44 ) * normalize( inNV );
    vec3  normalV = mat3( u_viewMat44 ) * modelNV;
    vec3  lightV  = normalize( -u_lightDir );
    NdotL         = max( 0.0, dot( normalV, lightV ) );
    texCoord      = inTex;

    vec4 modelPos = u_modelMat44 * vec4( inPos, 1.0 );
    vec4 viewPos  = u_viewMat44 * modelPos;
    gl_Position   = u_projectionMat44 * viewPos;
}
</script>

<script id="draw-shader-fs" type="x-shader/x-fragment">
precision mediump float;
varying float     NdotL;
varying vec2      texCoord;
uniform sampler2D u_texture;

void main()
{
    vec3 texColor = texture2D( u_texture, texCoord.st ).rgb;
    vec3 lightCol = (0.2 + 0.8 * NdotL) * texColor.rgb;
    gl_FragColor  = vec4( lightCol.rgb, 1.0 );
}
</script>

<script id="post-shader-vs" type="x-shader/x-vertex">
precision mediump float;

attribute vec2 inPos;

varying   vec2 pos;

void main()
{
    pos = inPos;
    gl_Position = vec4( inPos, 0.0, 1.0 );
}
</script>

<script id="blurX-shader-fs" type="x-shader/x-fragment">
precision mediump float;

varying vec2 pos;

uniform sampler2D u_texture;
uniform vec2      u_textureSize;
uniform float     u_sigma;
uniform vec2      u_dir;

float CalcGauss( float x, float sigma )
{
    if ( sigma <= 0.0 )
        return 0.0;
	return exp( -(x*x) / (2.0 * sigma) ) / (2.0 * 3.14157 * sigma);
}

void main()
{
    vec2 texC     = pos.st * 0.5 + 0.5;
    vec4 texCol   = texture2D( u_texture, texC );
    vec4 gaussCol = vec4( texCol.rgb, 1.0 );
    vec2 step     = u_dir / u_textureSize;
    for ( int i = 1; i <= 32; ++ i )
    {
        float weight = CalcGauss( float(i) / 32.0, u_sigma * 0.5 );
        if ( weight < 1.0/255.0 )
            break;
        texCol    = texture2D( u_texture, texC + step * float(i) );
        gaussCol += vec4( texCol.rgb * weight, weight );
        texCol    = texture2D( u_texture, texC - step * float(i) );
        gaussCol += vec4( texCol.rgb * weight, weight );
    }
    gaussCol.rgb = clamp( gaussCol.rgb / gaussCol.w, 0.0, 1.0 );
    gl_FragColor = vec4( gaussCol.rgb, 1.0 );
}
</script>

<style>
html,body { margin: 0; overflow: hidden; }
#gui { position : absolute; top : 0; left : 0; font-size : large; }
#ref-link { position : absolute; bottom : 0; left : 0; font-size : large; }  
</style>

<body>

<form id="gui" name="inputs">
<table>
    <tr> <td> <font color= #CCF>blur</font> </td> <td> <input type="range" id="sigma" min="0" max="100" value="50"/></td> </tr>
</table>
</form>

<canvas id="blur-canvas" style="border: none;"></canvas>

<a id="ref-link" href="https://stackoverflow.com/questions/11282394/what-kind-of-blurs-can-be-implemented-in-pixel-shaders/45878733#45878733">
<font color= #CCF>What kind of blurs can be implemented in pixel shaders?</font>
</a>

</body>

<script type="text/javascript">

(function loadscene() {

var sliderScale = 100.0
var gl;
var vp_size;
var canvas;
var camera;
var blurFB;
var progDraw;
var progPost;
var bufObj = {};
var bufSphere = {};
var textureObj;
var bufQuad = {};
var progDraw; 
var progBlur;

function render(deltaMS){

    var shininess = 10.0;
    var sigma = document.getElementById( "sigma" ).value / sliderScale;
    
    // setup view projection and model
    vp_size = [canvas.width, canvas.height];
    camera.Update( vp_size );
    var prjMat = camera.Perspective();
    var viewMat = camera.Orbit();
    var modelMat = IdentM44();
    modelMat = camera.AutoModelMatrix();
         
    gl.enable( gl.DEPTH_TEST );
    gl.clearColor( 0.0, 0.0, 0.0, 1.0 );

    // set up framebuffer
    gl.bindFramebuffer( gl.FRAMEBUFFER, blurFB[0] );
    gl.viewport( 0, 0, blurFB[0].width, blurFB[0].height );
    gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, blurFB[0].color0_texture, 0 );
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
    
    var texUnitSphere = 0;
    gl.activeTexture( gl.TEXTURE0 + texUnitSphere );
    gl.bindTexture( gl.TEXTURE_2D, textureObj );
    
    // set up draw shader
    ShProg.Use( progDraw );
    ShProg.SetM44( progDraw, "u_projectionMat44", prjMat );
    ShProg.SetM44( progDraw, "u_viewMat44", viewMat );
    ShProg.SetF3( progDraw, "u_lightDir", [-1.0, -0.5, -2.0] )
    ShProg.SetF3( progDraw, "u_color", [1.0, 0.5, 0.0] )
    var modelMat = IdentM44()
    modelMat = RotateAxis( modelMat, CalcAng( deltaMS, 13.0 ), 0 );
    modelMat = RotateAxis( modelMat, CalcAng( deltaMS, 17.0 ), 1 );
    ShProg.SetM44( progDraw, "u_modelMat44", modelMat );
    ShProg.SetI1( progDraw, "u_texture", texUnitSphere );
    
    // draw scene
    bufObj = bufSphere;
    gl.enableVertexAttribArray( progDraw.inPos );
    gl.enableVertexAttribArray( progDraw.inNV );
    gl.enableVertexAttribArray( progDraw.inTex );
    gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
    gl.vertexAttribPointer( progDraw.inPos, 3, gl.FLOAT, false, 0, 0 );
    gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.nv );
    gl.vertexAttribPointer( progDraw.inNV, 3, gl.FLOAT, false, 0, 0 );
    gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.tex );
    gl.vertexAttribPointer( progDraw.inTex, 2, gl.FLOAT, false, 0, 0 );
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
    gl.drawElements( gl.TRIANGLES, bufObj.inxLen, gl.UNSIGNED_SHORT, 0 );
    gl.disableVertexAttribArray( progDraw.inPos );
    gl.disableVertexAttribArray( progDraw.inNV );
    gl.disableVertexAttribArray( progDraw.intex );

    // set blur-X framebuffer and bind frambuffer texture
    gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0 );
    gl.bindFramebuffer( gl.FRAMEBUFFER, blurFB[1] );
    gl.viewport( 0, 0, blurFB[1].width, blurFB[1].height );
    gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, blurFB[1].color0_texture, 0 );
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
    var texUnit = 1;
    gl.activeTexture( gl.TEXTURE0 + texUnit );
    gl.bindTexture( gl.TEXTURE_2D, blurFB[0].color0_texture );

    // set up blur-X shader
    ShProg.Use( progBlur );
    ShProg.SetI1( progBlur, "u_texture", texUnit )
    ShProg.SetF2( progBlur, "u_textureSize", [ fb.width, fb.height ] );
    ShProg.SetF1( progBlur, "u_sigma", sigma )
    ShProg.SetF2( progBlur, "u_dir", [1.0, 0.0] )
    
    // draw full screen space
    gl.enableVertexAttribArray( progBlur.inPos );
    gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos );
    gl.vertexAttribPointer( progBlur.inPos, 2, gl.FLOAT, false, 0, 0 ); 
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx );
    gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
    gl.disableVertexAttribArray( progBlur.pos );

    // reset framebuffer and bind frambuffer texture
    gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0 );
    gl.bindFramebuffer( gl.FRAMEBUFFER, null );
    gl.viewport( 0, 0, canvas.width, canvas.height );
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
    texUnit = 2;
    gl.activeTexture( gl.TEXTURE0 + texUnit );
    gl.bindTexture( gl.TEXTURE_2D, blurFB[1].color0_texture );

    // set up pst process shader
    ShProg.SetI1( progBlur, "u_texture", texUnit )
    ShProg.SetF2( progBlur, "u_textureSize", [ fb.width, fb.height ] );
    ShProg.SetF1( progBlur, "u_sigma", sigma );
    ShProg.SetF2( progBlur, "u_dir", [0.0, 1.0] )
    
    // draw full screen space
    gl.enableVertexAttribArray( progBlur.inPos );
    gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos );
    gl.vertexAttribPointer( progBlur.inPos, 2, gl.FLOAT, false, 0, 0 ); 
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx );
    gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
    gl.disableVertexAttribArray( progBlur.pos );

    requestAnimationFrame(render);
}

function initScene() {

    canvas = document.getElementById( "blur-canvas");
    vp_size = [canvas.width, canvas.height];
    gl = canvas.getContext( "experimental-webgl" );
    if ( !gl )
      return;

    progDraw = ShProg.Create( 
      [ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "draw-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    progDraw.inPos = ShProg.AttrI(progDraw, "inPos");
    progDraw.inNV = ShProg.AttrI(progDraw, "inNV");
    progDraw.inTex = ShProg.AttrI(progDraw, "inTex");
    if ( progDraw.progObj == 0 )
        return;
  

    progBlur = ShProg.Create( 
      [ { source : "post-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "blurX-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    progBlur.inPos = ShProg.AttrI(progBlur, "inPos" );
    if ( progBlur.progObj == 0 )
        return;    

    // create sphere vertices
    var layer_size = 16, circum_size = 32, radius = 1.0;
    var circCnt = circum_size;
    var circCnt_2 = circCnt / 2;
    var layerCount = layer_size;
    for ( var tbInx = 0; tbInx <= layerCount; tbInx ++ )
    {
        var v = ( 1.0 - tbInx / layerCount );
        var heightFac = Math.sin( ( 1.0 - 2.0 * tbInx / layerCount ) * Math.PI/2.0 );
        var cosUp = Math.sqrt( 1.0 - heightFac * heightFac );
        var z = heightFac;
        for ( var i = 0; i <= circCnt_2; i ++ )
        {
          var u = i / circCnt_2;
          var angle = Math.PI * u;
          var x = Math.cos( angle ) * cosUp;
          var y = Math.sin( angle ) * cosUp;
          AddVertex( x * radius, y * radius, z * radius, x, y, z, u, v );
        }
        for ( var i = 0; i <= circCnt_2; i ++ )
        {
          var u = i / circCnt_2;
          var angle = Math.PI * u + Math.PI;
          var x = Math.cos( angle ) * cosUp;
          var y = Math.sin( angle ) * cosUp;
          AddVertex( x * radius, y * radius, z * radius, x, y, z, u, v );
        }
    }
    
    // bottom cap
    var circSize_2 = circCnt_2 + 1;
    var circSize = circSize_2 * 2;
    for ( var i = 0; i < circCnt_2; i ++ )
        AddFace( circSize + i, circSize + i + 1, i );
    for ( var i = circCnt_2+1; i < 2*circCnt_2+1; i ++ )
        AddFace( circSize + i, circSize + i + 1, i );

    // discs
    for ( var tbInx = 1; tbInx < layerCount - 1; tbInx ++ )
    {
        var ringStart = tbInx * circSize;
        var nextRingStart = (tbInx+1) * circSize;
        for ( var i = 0; i < circCnt_2; i ++ )
            AddFace( ringStart + i, nextRingStart + i, nextRingStart + i + 1, ringStart + i + 1 );
        ringStart += circSize_2;
        nextRingStart += circSize_2;
        for ( var i = 0; i < circCnt_2; i ++ )
            AddFace( ringStart + i, nextRingStart + i, nextRingStart + i + 1, ringStart + i + 1 );
    }

    // top cap
    var start = (layerCount-1) * circSize;
    for ( var i = 0; i < circCnt_2; i ++ )
        AddFace( start + i + 1, start + i, start + i + circSize );
    for ( var i = circCnt_2+1; i < 2*circCnt_2+1; i ++ )
        AddFace( start + i + 1, start + i, start + i + circSize );
    
    bufSphere.pos = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufSphere.pos );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( sphere_pts ), gl.STATIC_DRAW );
    bufSphere.nv = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufSphere.nv );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( sphere_nv ), gl.STATIC_DRAW );
    bufSphere.tex = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufSphere.tex );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( sphere_tex ), gl.STATIC_DRAW );
    bufSphere.inx = gl.createBuffer();
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufSphere.inx );
    gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( sphere_inx ), gl.STATIC_DRAW );
    bufSphere.inxLen = sphere_inx.length;

    var texCX = 128;
    var texCY = 128;
    var texPlan = [];
    for (ix = 0; ix < texCX; ++ix) {
        for (iy = 0; iy < texCY; ++iy) {
            var val_x = Math.sin( Math.PI * 12.0 * ix / texCX )
            var val_y = Math.sin( Math.PI * 12.0 * iy / texCY )
            var r = val_x < 0 ? 0 : 255;
            var g = val_y < 0 ? 0 : 255;
            var b = val_x < 0 && val_y < 0 ? 255 : 0;
            texPlan.push( r, g, b, 255 );
        }
    }
    textureObj = gl.createTexture();
    gl.activeTexture( gl.TEXTURE0 );
    gl.bindTexture( gl.TEXTURE_2D, textureObj );
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, texCX, texCY, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array( texPlan ) );
    gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, true );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT );

    //textureObj = Texture.LoadTexture2D( "https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/supermario.jpg" );    
    //textureObj = Texture.LoadTexture2D( "https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/worldmap1.png" ); 

    bufQuad.pos = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( [ -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ] ), gl.STATIC_DRAW );
    bufQuad.inx = gl.createBuffer();
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx );
    gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] ), gl.STATIC_DRAW );

    camera = new Camera( [0, 1.5, 0.0], [0, 0, 0], [0, 0, 1], 90, vp_size, 0.5, 100 );

    window.onresize = resize;
    resize();
    requestAnimationFrame(render);
}

function resize() {
    //vp_size = [gl.drawingBufferWidth, gl.drawingBufferHeight];
    vp_size = [window.innerWidth, window.innerHeight];
    //vp_size = [256, 256]
    canvas.width = vp_size[0];
    canvas.height = vp_size[1];

    var fbsize = Math.max(vp_size[0], vp_size[1]);
    fbsize = 1 << 31 - Math.clz32(fbsize); // nearest power of 2

    blurFB = [];
    for ( var i = 0; i < 2; ++ i ) {
        fb = gl.createFramebuffer();
        fb.width = fbsize;
        fb.height = fbsize;
        gl.bindFramebuffer( gl.FRAMEBUFFER, fb );
        fb.color0_texture = gl.createTexture();
        gl.bindTexture( gl.TEXTURE_2D, fb.color0_texture );
        gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
        gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
        gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, fb.width, fb.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
        fb.renderbuffer = gl.createRenderbuffer();
        gl.bindRenderbuffer( gl.RENDERBUFFER, fb.renderbuffer );
        gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, fb.width, fb.height );
        gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, fb.color0_texture, 0 );
        gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, fb.renderbuffer );
        gl.bindTexture( gl.TEXTURE_2D, null );
        gl.bindRenderbuffer( gl.RENDERBUFFER, null );
        gl.bindFramebuffer( gl.FRAMEBUFFER, null );
        blurFB.push( fb );
    }
}

var sphere_pts = [];
var sphere_nv = [];
var sphere_tex = [];
var sphere_inx = [];
function AddVertex( x, y, z, nvX, nvY, nvZ, u, v )
{
     sphere_pts.push( x, y, z );
     sphere_nv.push( nvX, nvY, nvZ );
     sphere_tex.push( u, v ); 
}
function AddFace( i1, i2, i3, i4 )  {
    sphere_inx.push( i1, i2, i3 );
    if ( i4 )
        sphere_inx.push( i1, i3, i4 );
}

var Texture = {};
Texture.HandleLoadedTexture2D = function( image, texture, flipY ) {
    gl.activeTexture( gl.TEXTURE0 );
    gl.bindTexture( gl.TEXTURE_2D, texture );
    gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, flipY != undefined && flipY == true );
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT );
    gl.bindTexture( gl.TEXTURE_2D, null );
    return texture;
}
Texture.LoadTexture2D = function( name ) {
    var texture = gl.createTexture();
    texture.image = new Image(64,64);
    texture.image.setAttribute('crossorigin', 'anonymous');
    texture.image.onload = function () {
        var canvas = document.createElement( 'canvas' );
        canvas.width = 512;
        canvas.height = 256;
        var context = canvas.getContext( '2d' );
        context.drawImage( texture.image, 0, 0, canvas.width, canvas.height );
        Texture.HandleLoadedTexture2D( canvas, texture, true )
    }
    texture.image.src = name;
    return texture;
}

function IdentM44() {
    return [ 1, 0, 0, 0,    0, 1, 0, 0,    0, 0, 1, 0,    0, 0, 0, 1 ];
};

function RotateAxis(matA, angRad, axis) {
    var aMap = [ [1, 2], [2, 0], [0, 1] ];
    var a0 = aMap[axis][0], a1 = aMap[axis][1]; 
    var sinAng = Math.sin(angRad), cosAng = Math.cos(angRad);
    var matB = matA.slice(0);
    for ( var i = 0; i < 16; ++ i ) matB[i] = matA[i];
    for ( var i = 0; i < 3; ++ i ) {
        matB[a0*4+i] = matA[a0*4+i] * cosAng + matA[a1*4+i] * sinAng;
        matB[a1*4+i] = matA[a0*4+i] * -sinAng + matA[a1*4+i] * cosAng;
    }
    return matB;
}

function Rotate(matA, angRad, axis) {
    var s = Math.sin(angRad), c = Math.cos(angRad);
    var x = axis[0], y = axis[1], z = axis[2]; 
    matB = [
        x*x*(1-c)+c,   x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0,
        y*x*(1-c)+z*s, y*y*(1-c)+c,   y*z*(1-c)-x*s, 0,
        z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c,   0,
        0,             0,             0,             1 ];
    return Multiply(matA, matB);
}    

function Multiply(matA, matB) {
    matC = IdentM44();
    for (var i0=0; i0<4; ++i0 )
        for (var i1=0; i1<4; ++i1 )
            matC[i0*4+i1] = matB[i0*4+0] * matA[0*4+i1] + matB[i0*4+1] * matA[1*4+i1] + matB[i0*4+2] * matA[2*4+i1] + matB[i0*4+3] * matA[3*4+i1]  
    return matC;
}

function Cross( a, b ) { return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], 0.0 ]; }
function Dot( a, b ) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }
function Normalize( v ) {
    var len = Math.sqrt( v[0] * v[0] + v[1] * v[1] + v[2] * v[2] );
    return [ v[0] / len, v[1] / len, v[2] / len ];
}

Camera = function( pos, target, up, fov_y, vp, near, far ) {
this.Time = function() { return Date.now(); }
this.pos = pos;
this.target = target;
this.up = up;
this.fov_y = fov_y;
this.vp = vp;
this.near = near;
this.far = far;
this.orbit_mat = this.current_orbit_mat = this.model_mat = this.current_model_mat = IdentM44();
this.mouse_drag = this.auto_spin = false;
this.auto_rotate = true;
this.mouse_start = [0, 0];
this.mouse_drag_axis = [0, 0, 0];
this.mouse_drag_angle = 0;
this.mouse_drag_time = 0;
this.drag_start_T = this.rotate_start_T = this.Time();
this.Ortho = function() {
    var fn = this.far + this.near;
    var f_n = this.far - this.near;
    var w = this.vp[0];
    var h = this.vp[1];
    return [
        2/w, 0,   0,       0,
        0,   2/h, 0,       0,
        0,   0,   -2/f_n,  0,
        0,   0,   -fn/f_n, 1 ];
};  
this.Perspective = function() {
    var n = this.near;
    var f = this.far;
    var fn = f + n;
    var f_n = f - n;
    var r = this.vp[0] / this.vp[1];
    var t = 1 / Math.tan( Math.PI * this.fov_y / 360 );
    return [
        t/r, 0, 0,          0,
        0,   t, 0,          0,
        0,   0, -fn/f_n,   -1,
        0,   0, -2*f*n/f_n, 0 ];
}; 
this.LookAt = function() {
    var mz = Normalize( [ this.pos[0]-this.target[0], this.pos[1]-this.target[1], this.pos[2]-this.target[2] ] );
    var mx = Normalize( Cross( this.up, mz ) );
    var my = Normalize( Cross( mz, mx ) );
    var tx = Dot( mx, this.pos );
    var ty = Dot( my, this.pos );
    var tz = Dot( [-mz[0], -mz[1], -mz[2]], this.pos ); 
    return [mx[0], my[0], mz[0], 0, mx[1], my[1], mz[1], 0, mx[2], my[2], mz[2], 0, tx, ty, tz, 1]; 
};
this.Orbit = function() {
    return Multiply(this.LookAt(), this.OrbitMatrix());
}; 
this.OrbitMatrix = function() {
    return (this.mouse_drag || (this.auto_rotate && this.auto_spin)) ? Multiply(this.current_orbit_mat, this.orbit_mat) : this.orbit_mat;
};
this.AutoModelMatrix = function() {
    return this.auto_rotate ? Multiply(this.current_model_mat, this.model_mat) : this.model_mat;
};
this.Update = function(vp_size) {
    if (vp_size)
        this.vp = vp_size;
    var current_T = this.Time();
    this.current_model_mat = IdentM44()
    if (this.mouse_drag) {
        this.current_orbit_mat = Rotate(IdentM44(), this.mouse_drag_angle, this.mouse_drag_axis);
    } else if (this.auto_rotate) {
        if (this.auto_spin ) {
            if (this.mouse_drag_time > 0 ) {
                var angle = this.mouse_drag_angle * (current_T - this.rotate_start_T) / this.mouse_drag_time;
                this.current_orbit_mat = Rotate(IdentM44(), angle, this.mouse_drag_axis);
            }
        } else {
            var auto_angle_x = Fract( (current_T - this.rotate_start_T) / 13000.0 ) * 2.0 * Math.PI;
            var auto_angle_y = Fract( (current_T - this.rotate_start_T) / 17000.0 ) * 2.0 * Math.PI;
            this.current_model_mat = RotateAxis( this.current_model_mat, auto_angle_x, 0 );
            this.current_model_mat = RotateAxis( this.current_model_mat, auto_angle_y, 1 );
        }
    }
};
this.ChangeMotionMode = function(drag, spin, auto ) {
    var new_drag = drag;
    var new_auto = new_drag ? false : auto;
    var new_spin = new_auto ? spin : false;
    change = this.mouse_drag != new_drag || this.auto_rotate != new_auto || this.auto_spin != new_spin; 
    if (!change)
        return;
    if (new_drag && !this.mouse_drag) {
        this.drag_start_T = this.Time();
        this.mouse_drag_angle = 0.0;
        this.mouse_drag_time = 0;
    }
    if (new_auto && !this.auto_rotate)
        this.rotate_start_T = this.Time();
    this.mouse_drag = new_drag; 
    this.auto_rotate = new_auto;  
    this.auto_spin = new_spin;
    this.orbit_mat = Multiply(this.current_orbit_mat, this.orbit_mat);
    this.current_orbit_mat = IdentM44();
    this.model_mat = Multiply(this.current_model_mat, this.model_mat);
    this.current_model_mat = IdentM44();
};
this.OnMouseDown = function( event ) {
    var rect = gl.canvas.getBoundingClientRect();
    if ( event.clientX < rect.left || event.clientX > rect.right ) return;
    if ( event.clientY < rect.top || event.clientY > rect.bottom ) return;
    if (event.button == 0) { // left button
        this.mouse_start = [event.clientX, event.clientY]; 
        this.ChangeMotionMode( true, false, false );
    }
};
this.OnMouseUp = function( event ) {
    if (event.button == 0) { // left button
        this.ChangeMotionMode( false, true, true );
    } else if (event.button == 1) {// middle button
        this.ChangeMotionMode( false, false, !this.auto_rotate );
    }
};
this.OnMouseMove = function( event ) {
    var dx = (event.clientX-this.mouse_start[0]) / this.vp[0];
    var dy = (event.clientY-this.mouse_start[1]) / this.vp[1];
    var len = Math.sqrt(dx*dx + dy*dy);
    if (this.mouse_drag && len > 0) {
        this.mouse_drag_angle = Math.PI*len;
        this.mouse_drag_axis = [dy/len, 0, -dx/len];
        this.mouse_drag_time = this.Time() - this.drag_start_T;
    }
};

this.domElement = document;
var cam = this;
//this.domElement.addEventListener( 'contextmenu', function(e) { event.preventDefault(); }, false );
this.domElement.addEventListener( 'mousedown', function(e) { cam.OnMouseDown(e) }, false );
this.domElement.addEventListener( 'mouseup', function(e) { cam.OnMouseUp(e) }, false );
this.domElement.addEventListener( 'mousemove', function(e) { cam.OnMouseMove(e) }, false );
//this.domElement.addEventListener( 'mousewheel', hid_events.onMouseWheel, false );
//this.domElement.addEventListener( 'DOMMouseScroll', hid_events.onMouseWheel, false ); // firefox
}

var ShProg = {
Create: function (shaderList) {
    var shaderObjs = [];
    for (var i_sh = 0; i_sh < shaderList.length; ++i_sh) {
        var shderObj = this.Compile(shaderList[i_sh].source, shaderList[i_sh].stage);
        if (shderObj) shaderObjs.push(shderObj);
    }
    var prog = {}
    prog.progObj = this.Link(shaderObjs)
    if (prog.progObj) {
        prog.attrInx = {};
        var noOfAttributes = gl.getProgramParameter(prog.progObj, gl.ACTIVE_ATTRIBUTES);
        for (var i_n = 0; i_n < noOfAttributes; ++i_n) {
            var name = gl.getActiveAttrib(prog.progObj, i_n).name;
            prog.attrInx[name] = gl.getAttribLocation(prog.progObj, name);
        }
        prog.uniLoc = {};
        var noOfUniforms = gl.getProgramParameter(prog.progObj, gl.ACTIVE_UNIFORMS);
        for (var i_n = 0; i_n < noOfUniforms; ++i_n) {
            var name = gl.getActiveUniform(prog.progObj, i_n).name;
            prog.uniLoc[name] = gl.getUniformLocation(prog.progObj, name);
        }
    }
    return prog;
},
AttrI: function (prog, name) { return prog.attrInx[name]; },
UniformL: function (prog, name) { return prog.uniLoc[name]; },
Use: function (prog) { gl.useProgram(prog.progObj); },
SetI1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1i(prog.uniLoc[name], val); },
SetF1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1f(prog.uniLoc[name], val); },
SetF2: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform2fv(prog.uniLoc[name], arr); },
SetF3: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform3fv(prog.uniLoc[name], arr); },
SetF4: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform4fv(prog.uniLoc[name], arr); },
SetM33: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix3fv(prog.uniLoc[name], false, mat); },
SetM44: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix4fv(prog.uniLoc[name], false, mat); },
Compile: function (source, shaderStage) {
    var shaderScript = document.getElementById(source);
    if (shaderScript)
        source = shaderScript.text;
    var shaderObj = gl.createShader(shaderStage);
    gl.shaderSource(shaderObj, source);
    gl.compileShader(shaderObj);
    var status = gl.getShaderParameter(shaderObj, gl.COMPILE_STATUS);
    if (!status) alert(gl.getShaderInfoLog(shaderObj));
    return status ? shaderObj : null;
},
Link: function (shaderObjs) {
    var prog = gl.createProgram();
    for (var i_sh = 0; i_sh < shaderObjs.length; ++i_sh)
        gl.attachShader(prog, shaderObjs[i_sh]);
    gl.linkProgram(prog);
    status = gl.getProgramParameter(prog, gl.LINK_STATUS);
    if ( !status ) alert(gl.getProgramInfoLog(prog));
    return status ? prog : null;
} };

function Fract( val ) { 
    return val - Math.trunc( val );
}
function CalcAng( deltaMS, intervall ) {
    return Fract( deltaMS / (1000*intervall) ) * 2.0 * Math.PI;
}
function CalcMove( deltaMS, intervall, range ) {
    var pos = self.Fract( deltaMS / (1000*intervall) ) * 2.0
    var pos = pos < 1.0 ? pos : (2.0-pos)
    return range[0] + (range[1] - range[0]) * pos;
}    
function EllipticalPosition( a, b, angRag ) {
    var a_b = a * a - b * b
    var ea = (a_b <= 0) ? 0 : Math.sqrt( a_b );
    var eb = (a_b >= 0) ? 0 : Math.sqrt( -a_b );
    return [ a * Math.sin( angRag ) - ea, b * Math.cos( angRag ) - eb, 0 ];
}

initScene();

})();
</script>
